﻿// See https://aka.ms/new-console-template for more information

using System.Text;
using System.Text.Json.Serialization;
using Example;
using Newtonsoft.Json;

Console.WriteLine("Hello, World!");

HttpClient sharedClient = new()
{
    BaseAddress = new Uri("http://localhost:4000"),
};


var userData = new
{
    username = "test",
    password = "test",
};
var json = JsonConvert.SerializeObject(userData);

// 创建HttpContent对象
HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");


using HttpResponseMessage response = await sharedClient.PostAsync("Users/authenticate",content);
response.EnsureSuccessStatusCode();

var jsonResponse = await response.Content.ReadAsStringAsync();
var token = JsonConvert.DeserializeObject<TokenResponse>(jsonResponse);

if (token != null)
{
    sharedClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.token}");
    sharedClient.DefaultRequestHeaders.Add("RefreshToken", token.refreshToken);
}

Console.WriteLine($"{jsonResponse}\n");

for (int i = 0; i < 100; i++)
{
    await Task.Delay(5000);
    HttpResponseMessage weatherResponse = await sharedClient.GetAsync("Users");
    if (weatherResponse.ReasonPhrase is "OK")
    {
        var jsonWeatherResponse = await weatherResponse.Content.ReadAsStringAsync();
        Console.WriteLine($"{i} {weatherResponse.ReasonPhrase}\n");
    }
    else
    {
        Console.WriteLine($"{i} {weatherResponse.ReasonPhrase}\n");
    }
}